// 引入接口文件
import { addFun,editFun,queryInfo,getProjectPermission,findByCity,queryAllAddress,queryMonthList,getPriceRatio} from './monthReportDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  btnLoading: false,
  tableData:[],
  areaList: [],
  cityList: [],
  countyList: [],
  loading: false,
  keys: 0,
  actionType: 'add',
  optionData:{
    mianji:[],
    xingong:[],
    yuefen:[],
    junjia:[]
  },
  query: {
    id: '',
    reason:'',
    quantityRatio: '',
    acreageRatio: '',
    dataSources: '',
    salesAmount: '',
    averagePrice: '',
    averageRatio: '',
    transactionAcreage: '',
    monthlyStatus:'0',
    addAcreage: '',
    city:'',
    cityCode: '',
    area: '',
    areaCode: '',
    month: '',
    region:'',
    regionCode:'',
    createBy:localStorage.nickname,
    createUser:localStorage.username,
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          if(query.actionType == 'check'|| query.actionType == 'edit'){
            dispatch({type: 'queryInfo',payload: {id:query.id}})
          }
          dispatch({type: 'getProjectPermission',payload: {}})
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    // 获取县级
      *getCountyList({ payload }, { put, call, select }) {
        let {countyList,cityList} = yield select(state => state[tmpModule.namespace])
          let cityName = cityList.filter(item =>item.cityid == payload.cityid)[0].city
          let params = { 
            cityId: payload.cityid
          }
          const data = yield call(queryAllAddress,params)
          if (data.success) {
            countyList =  data.result.map((item,index)=>{
              return {
                label: item.region,
                value: item.id,
              }
            })
              yield put({ type: 'updateStore', payload: { countyList } });
          }
      },
      *getProjectPermission({payload}, {put, select, call}){
          let {areaList} = yield select(state => state[tmpModule.namespace])
          let params = { 
            userId: localStorage.username
          }
          const { success,projectList} = yield call(getProjectPermission, {...params})
          if(success){
          areaList =  projectList.map((item,index)=>{
                        return {
                          label: item.areaName,
                          value: item.areaId,
                        }
                      })
            yield put({
              type: 'updateStore',
              payload: {areaList}
            })
          }
      },
      *findByCity({payload}, {put, select, call}){
        let {cityList,actionType,query} = yield select(state => state[tmpModule.namespace])
        let params = { 
          area: payload.areaId,
        }
        const { success,result} = yield call(findByCity, {...params})
        if(success){
          cityList = result.filter(item => !!item)
          yield put({
            type: 'updateStore',
            payload: {cityList}
          })
          if(actionType == 'edit'||actionType == 'check'){
            yield put({type: 'getCountyList',payload: {cityid:query.cityCode}})
          }
        }
      },
      *queryMonthList({payload}, {put, select, call}){
        let {tableData,query,optionData} = yield select(state => state[tmpModule.namespace])
        let params = { 
          area: query.areaCode,
          beginTime: query.month,
          city: query.cityCode,
          region: query.regionCode,
        }
        const { success,result} = yield call(queryMonthList, {...params})
        if(success){
          tableData = result
          for(var item of result){
            optionData.yuefen.push(item.month)
            optionData.xingong.push(item.addAcreage)
            optionData.mianji.push(item.transactionAcreage)
            optionData.junjia.push(item.averagePrice)
          }
          yield put({
            type: 'updateStore',
            payload: {tableData,optionData}
          })
        }
      },
      *getPriceRatio({payload}, {put, select, call}){
        let {query} = yield select(state => state[tmpModule.namespace])
        let params = { 
          area: query.areaCode,
          beginTime: query.month,
          city: query.cityCode,
          region: query.regionCode,
          ro: query.addAcreage,
          transactionAcreage: query.transactionAcreage,
          ta: query.averagePrice,
        }
        const { success,result} = yield call(getPriceRatio, {...params})
        if(success){
          query.quantityRatio = result.quantityRatio
          query.averageRatio = result.averageRatio
          query.acreageRatio = result.acreageRatio
          query.salesAmount = result.salesAmount
          yield put({
            type: 'updateStore',
            payload: {query}
          })
        }
      },
      // 查询记录
      *queryInfo({payload}, {put, select, call}){
          let {query} = yield select(state => state[tmpModule.namespace])
          let params = { 
            id: payload.id,
          }
          const { success,result} = yield call(queryInfo, {...params})
          if(success){
            query = result
            yield put({
              type: 'updateStore',
              payload: {query}
            })
            yield put({type: 'findByCity',payload: {areaId:query.areaCode}})
            yield put({type: 'queryMonthList',payload: {}})
          }
      },
      *submit({payload},{put,select,call}){
        let {btnLoading,actionType,query,areaList,cityList,countyList} = yield select(state => state[tmpModule.namespace])
        for(var itt of areaList){
          if(itt.value == query.areaCode){
            query.area = itt.label
          }
        }
        for(var itt of cityList){
          if(itt.cityid == query.cityCode){
            query.city = itt.city
          }
        }
        for(var itt of countyList){
          if(itt.value == query.regionCode){
            query.region = itt.label
          }
        }
        if(!query.regionCode){
          query.region = ''
        }
        let params = query
        btnLoading = true
        yield put({type: 'updateStore', payload: {btnLoading}})
        if(actionType == 'add'){
          let { success, msg, data } = yield call(addFun, {...params})
          let flag = success.toString()
          if(flag){
            btnLoading = false
            yield put({type: 'updateStore', payload: {btnLoading}})
          }
          if(success){
            message.success('提交成功')
            hashHistory.push({
              pathname: '/home/predictManage/monthReport',
              query: {}
            })
          }
        }
        if(actionType == 'edit'){
          let { success, msg, data } = yield call(editFun, {...params})
          let flag = success.toString()
          if(flag){
            btnLoading = false
            yield put({type: 'updateStore', payload: {btnLoading}})
          }
          if(success){
            message.success('提交成功')
            hashHistory.push({
              pathname: '/home/predictManage/monthReport',
              query: {}
            })
          }
        }
      }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
